

import java.util.Arrays;
import java.util.List;

import messagepasser.ClockFactory;
import messagepasser.ClockService;
import messagepasser.DocPermissions;
import messagepasser.Document;
import messagepasser.Message;
import messagepasser.MessagePasser;
import messagepasser.TimeStampedMessage;
import messagepasser.UserInfo;



public class TextChat implements Runnable {

	
	
	public LoggedIn log;
	UserInfo me=null;
	ClockFactory factory = new ClockFactory();
	ClockService clock = factory.getInstance("Vector");
    UserInfo[] users=null;
    List<UserInfo>  usersList =null; 
    String destination;
    Document chatDoc;
    DocPermissions docPerm;
    MessagePasser msgPsr;
    	   	
    	
	public TextChat(UserInfo me,UserInfo[] users,LoggedIn log){
		this.log = log;
        this.me=me;
        this.users=users;
       
	}
	
	public void setDocPasser(Document chatDoc){
		this.chatDoc=chatDoc;
		this.msgPsr=this.chatDoc.getMyPasser();
		System.out.println("Setting msgPsr for chatDoc");
		
	}
	@Override
	public void run() {
		System.out.println("In run");
		
		
		//System.out.println("in run of textchat msgpasr" + this.msgPsr);
           //Message data1 = chatDoc.getMyPasser().receive();
           //if (data1 != null) {
		
		/*if(this.msgPsr == null){
			System.out.println("NuLLLLL MSGGGG PAAASSSEEEERRRR");
		}*/
		
		while(true){
			Message data1 = chatDoc.getMyPasser().receive();
				
		if (data1!=null) {
			System.out.println("Just checking not nullll*********************************");
			
			System.out.println("Message received:" + data1);
			if(data1.getMsgType().equals("TEXT")){
				System.out.println("Message recived inside IF:" + data1);
				
				String tokens[] = data1.getHeader().getSrc().split("@");
				log.jTextArea1.append("\n" + tokens[0] + ":"+data1.getPayload().toString());
							}
		}
		
			
		}

	}


	public void sendChatMsg(String destination,String getText) {
		this.destination=destination;
		
		TimeStampedMessage msg = new TimeStampedMessage(destination, me
				.getUsername(), "1000", "1000", getText,false,false);
		msg.setMsgType("TEXT");
		msg.setMulticastMsg(false);
		
		System.out.println("textChat send msg is :"+msg.getPayload().toString());
		msg.getHeader().setId(chatDoc.getDocId() + "");
		
		
		this.msgPsr=chatDoc.getMyPasser();
		
		System.out.println("textChat send after getMyPasser");
		
		msgPsr.send(msg);
		
	}
}
